package com.kingschan.jeasytag.sql.parse.fieldtype;

import org.json.JSONObject;
import com.kingschan.jeasytag.sql.parse.AbstractAnalysis;
import com.kingschan.util.lang.StringUtil;
/**
 * DateboxAnalysis
 * @author kingschan
 *date:2013-4-24
 */
public class DateboxAnalysis extends AbstractAnalysis{
	
	/**
	 *validation
	 * @param filter
	 * @return
	 * @throws Exception
	 */
	private boolean validation(JSONObject filter)throws Exception {
		String operactor=AbstractAnalysis.Operator.get(filter.getString("Operator"));
		if ("".equals(StringUtil.ConvertNullStr(filter.getString("value")))) {
			return false;
		}
		else if (operactor.equals("Contain")||operactor.equals("likeLeft")||operactor.equals("likeRight")) {
			return false;
		}else{
			return true;
		}
		
	}
	
	@Override
	protected String mysqlAnalysis(JSONObject filter) throws Exception {
		//date_format(field,'%Y-%m-%d')
		if (validation(filter)) {
			String operactor=AbstractAnalysis.Operator.get(filter.getString("Operator"));
			StringBuffer sb = new StringBuffer();			
			sb.append("date_format(").append(filter.getString("filterfield")).append(", '%Y-%m-%d')")
			.append(operactor).append("'")
			.append(filter.getString("value"))
			.append("'")
			;
			return sb.toString();
		}else {
			return "";
		}
		
	}

	@Override
	protected String oracleAnalysis(JSONObject filter) throws Exception {
		//lock_date >= to_date('2010-04-02','YYYY-mm-dd');
		if (validation(filter)) {
			String operactor=AbstractAnalysis.Operator.get(filter.getString("Operator"));
			StringBuffer sb = new StringBuffer();			
			sb.append(filter.getString("filterfield"))
			.append(operactor)
			.append("to_date('").append(filter.getString("value")).append("','YYYY-mm-dd')")
			
			;
			return sb.toString();
		}else {
			return "";
		}
	}

	@Override
	protected String sqlserverAnalysis(JSONObject filter) throws Exception {		
		//CONVERT(varchar(100), GETDATE(), 23):
		if (validation(filter)) {
			String operactor=AbstractAnalysis.Operator.get(filter.getString("Operator"));
			StringBuffer sb = new StringBuffer();			
			sb.append(" CONVERT(varchar(10),").append(filter.getString("filterfield")).append(",23) as ").append(filter.getString("filterfield"))	
			.append(operactor)
			.append("'")
			.append(filter.getString("value"))
			.append("'")
			;
			return sb.toString();
		}else {
			return "";
		}
	}

}
